<?php

namespace addons\cms\model;

use app\common\library\Auth;
use app\common\library\Email;
use think\Exception;
use think\Model;
use think\Validate;

/**
 * 评论模型
 */
class Archives_user Extends Model
{

    protected $name = "cms_archives_user";
    //自定义初始化
    protected static function init()
    {

    }


    /**
     * 发表评论
     * @param array $params
     * @return bool
     * @throws Exception
     */
    public static function postComment($archives_id)
    {
        $request = request();
        $request->filter('strip_tags');
        $useragent = $request->server('HTTP_USER_AGENT', '');
        $ip = $request->ip();
        $auth = Auth::instance();

        if (!$auth->id) {
            return [
                'code'=>-1,
                'msg'=>"请登录后进行收藏"
            ];
        }
        //查找是否收藏
        $is_collection = self::where(['archives_id' =>$archives_id, 'user_id' =>  $auth->id])->find();
        if ($is_collection) {
            return [
                'code'=>-1,
                'msg'=>"你已经收藏过了,请勿重复操作"
            ];
        }

        $params['user_id'] = $auth->id;
        $params['archives_id'] = $archives_id;
        $params['createtime'] = date("Y-m-d H:i:s",time());
        (new static())->allowField(true)->save($params);

        return true;
    }


    /**
     * 取消关注
     * @param array $params
     * @return bool
     * @throws Exception
     */
    public static function qu_collection($id)
    {
        $request = request();
        $request->filter('strip_tags');
        $useragent = $request->server('HTTP_USER_AGENT', '');
        $ip = $request->ip();
        $auth = Auth::instance();

        if (!$auth->id) {
            return [
                'code'=>-1,
                'msg'=>"请登录后进行操作"
            ];
        }

        self::where(['archives_id' =>$id, 'user_id' =>  $auth->id])->delete();

        return true;
    }

    /**
     * 关联会员模型
     */
    public function user()
    {
        return $this->belongsTo("app\common\model\User")->field('id,nickname,avatar,email')->setEagerlyType(1);
    }

    /**
     * 关联文章模型
     */
    public function archives()
    {
        return $this->belongsTo("addons\cms\model\Archives")->field('id,title,image,diyname,description,collection,model_id,money,channel_id,likes,dislikes,tags,createtime')->setEagerlyType(1);
    }

}
